package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R insert(@RequestBody Category cat) {
        categoryService.save(cat);
        return R.success("添加成功!");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> categorylqw = new LambdaQueryWrapper<>();
        categorylqw.orderByAsc(Category::getSort);
        categoryService.page(categoryPage, categorylqw);
        return R.success(categoryPage);
    }

    @DeleteMapping
    public R deletebyid(Long id) {
        categoryService.delete(id);
        return R.success("删除成功!");
    }

    @PutMapping
    public R update(@RequestBody Category cat) {
        categoryService.updateById(cat);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category cat) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(cat.getType() != null, Category::getType, cat.getType());
        lqw.orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
